<template>
  <div id="scene" @drop="onDrop" @dragover.prevent="true">
    <div id="GameDiv">
      <canvas id="GameCanvas"
              @mousemove="onMouseMove"
              @mousedown="onMouseDown"
              @mouseup="onMouseUp"
              @mousewheel="onMouseWheel"
      ></canvas>
    </div>
    <div style="position: absolute;pointer-events: none; top:0;width: 100%;height: 100%;"
    >
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, onMounted } from 'vue';
import { bind } from 'size-sensor';
import engine from './engine/index';
import { IUiMenuItem, showMenuByMouseEvent } from '@/ui-kit/menu';
import SceneMenu from './menu';
import { sceneAssistant } from './index';
import { isMouseLeft, isMouseRight } from '../util/keyboard';
import { setCursor } from '../util/cursor';
import { Emitter } from '@/ui-kit/index';
import { ChoosePosition } from './msg';
import { DragCreateObjectData, DragType } from '../asset/dragHelper';
import { instanceGameObject } from './inquirer/crate-object/data';
import Mousetrap from 'mousetrap';

export default defineComponent({
  name: 's-scene',

  setup(props, { emit }) {
    let hasMouseMove = false;
    let hasMouseDown = false;

    onMounted(async () => {
      if (!engine.init) {

        await engine.load();
        sceneAssistant.init();
        updateEngineDesignResolutionSize();

        Mousetrap.bind(['backspace'], () => {
          sceneAssistant.deleteSelectNode();
        }, 'keydown');

        Emitter.on(ChoosePosition, () => {

        });
      }
    });

    function onSceneMenu(event: MouseEvent) {
      let menus: IUiMenuItem[] = [];
      if (sceneAssistant.selectNode) {
        menus = [
          {
            name: '删除',
            callback: () => {
              sceneAssistant.deleteSelectNode();
            },
          },
          {
            name: '复制',
            callback: () => {

            },
          },
          {
            name: '粘贴',
            callback: () => {

            },
          },
          {
            name: '置顶', callback: () => {

            },
          },
          {
            name: '上移', callback: () => {

            },
          },
          {
            name: '下移', callback: () => {

            },
          },
          {
            name: '置底', callback: () => {

            },
          },
        ];
      } else {
        menus = SceneMenu.Menus;
      }
      if (menus.length > 0) {
        showMenuByMouseEvent(event, menus);
      }
    }


    function onResize(el: HTMLDivElement) {
      const { width, height } = { width: el.clientWidth, height: el.clientHeight };
      if (width && height) {
        console.log(`width:${width}, height:${height}`);
        // @ts-ignore
        cc.Canvas.instance.designResolution = cc.size(width, height);
        // @ts-ignore
        cc.Canvas.instance.node.setPosition(width / 2, height / 2);
        // @ts-ignore
        cc.Canvas.instance.node.setContentSize(width, height);
        sceneAssistant.onResize(width, height);
      }
    }

    function updateEngineDesignResolutionSize() {
      const el: HTMLElement | null = document.getElementById('GameDiv');
      if (el) {
        const div = el as HTMLDivElement;
        onResize(div);
        bind(div, (element: HTMLDivElement | null) => {
          if (element) {
            onResize(element);
          }
        });
      }
    }


    return {
      onMouseDown(event: MouseEvent) {
        if (isMouseLeft(event)) {
          // @ts-ignore
          const size = cc.view.getDesignResolutionSize();
          const rect = { left: 0, top: 0, width: size.width, height: size.height };
          // @ts-ignore
          const position = cc.v2(event.offsetX, event.offsetY);
          // @ts-ignore
          cc.view._convertMouseToLocationInView(position, rect);
          // sceneAssistant.onSceneClick(position);
        }
        hasMouseMove = false;
        hasMouseDown = true;
      },

      onMouseMove(event: MouseEvent) {
        hasMouseMove = true;
        if (hasMouseDown) {
          if (isMouseRight(event)) {
            setCursor('move');
            event.stopPropagation();
            event.stopImmediatePropagation();
            sceneAssistant.onMove(event.movementX, event.movementY);
          }
        }
      },
      onMouseWheel(event: WheelEvent) {
        // todo wheelDelta
        sceneAssistant.onWheel(event.deltaY);
      },
      onMouseUp(event: MouseEvent) {
        setCursor();
        // 鼠标按下没有移动，说明要触发右键菜单
        if (!hasMouseMove) {
          if (isMouseRight(event)) {
            onSceneMenu(event);
          }
        }
      },
      async onDrop(event: DragEvent) {
        const str = event.dataTransfer?.getData(DragType.CreateObject);
        if (str) {
          const data = JSON.parse(str) as DragCreateObjectData;
          if (data) {
            await instanceGameObject(data.id);
          }
        }
      },
    };
  },
});

</script>

<style scoped lang="scss">
#scene {
  position: relative;
  width: 100%;
  height: 100%;

  #GameDiv {
    width: 100%;
    height: 100%;
    margin: 0 auto;
    background: #fafafa;
    position: relative;

    #GameCanvas {
      outline: none;
    }
  }
}
</style>